<template>
  <div class="app-container">
    <div :class="{showSearch:showSearch}">
      <Cards ref="cardRefs" class="mb20" :tabs="tabs" @cardSearch="onCardSearch" />
      <TheQueryForm
        ref="queryFormRefs"
        :option="searchOption"
        @onSubmit="onSubmit"
        @onClear="onClear"
      ></TheQueryForm>
    </div>

    <el-row style="margin-bottom: 20px">
      <el-col :span="18">
        <el-radio-group size="small" v-model="orderStatus" @change="onTabChange">
          <el-radio-button label>全部</el-radio-button>
          <el-radio-button label="WAIT_PAY" style="position: relative">
            待支付
            <el-badge
              v-if="statusCount.waitPayCount > 0"
              :value="statusCount.waitPayCount"
              :max="99"
              class="badge"
            ></el-badge>
          </el-radio-button>
          <el-radio-button label="WART_SEND">
            待派单
            <el-badge
              v-if="statusCount.waitSendCount > 0"
              :value="statusCount.waitSendCount"
              :max="99"
              class="badge"
            ></el-badge>
          </el-radio-button>
          <el-radio-button label="WART_APPOINTMENT">
            待预约
            <el-badge
              class="badge"
              v-if="statusCount.waitAppointmentCount > 0"
              :value="statusCount.waitAppointmentCount"
              :max="99"
            ></el-badge>
          </el-radio-button>
          <el-radio-button label="WART_SITE">
            待上门
            <el-badge
              v-if="statusCount.waitSiteCount > 0"
              :value="statusCount.waitSiteCount"
              :max="99"
              class="badge"
            ></el-badge>
          </el-radio-button>
          <el-radio-button label="WORKING">
            施工中
            <el-badge
              v-if="statusCount.workingCount > 0"
              :value="statusCount.workingCount"
              :max="99"
              class="badge"
            ></el-badge>
          </el-radio-button>
          <el-radio-button label="WART_CHECK">
            待验收
            <el-badge
              v-if="statusCount.waitCheckCount > 0"
              :value="statusCount.waitCheckCount"
              :max="99"
              class="badge"
            ></el-badge>
          </el-radio-button>
          <el-radio-button label="FINISH">订单完结</el-radio-button>
          <el-radio-button label="CANCEL">订单取消</el-radio-button>
          <el-radio-button label="REFUND_CLOSE">订单退款关闭</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="6" style="display: flex; justify-content: flex-end">
        <!-- <el-button size="small" type="primary" @click="handleCreateOrder()"
          >下单</el-button
        >-->
        <el-button :type="showSearch?'':'primary'" icon="el-icon-search" @click="onShowSearch">收起/展开筛选项</el-button>
        <el-button size="small" type="primary" @click="handleCreateOrder('liuGe')">代下单</el-button>
        <el-button size="small" :loading="exportLoading" @click="handleExport">导出Excel</el-button>
      </el-col>
    </el-row>
    <TheTable
      ref="tableRefs"
      :tableOption="tableOption"
      :pageNo.sync="pageNo"
      :limit.sync="limit"
      :api="queryPageApi"
      :queryParams="queryParams"
    />
    <el-dialog width="400px" title="请选择代下单的商家" :visible.sync="sassVisible" append-to-body>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item prop="sassId">
          <el-select v-model="ruleForm.merchantId" placeholder="请选择">
            <el-option
              v-for="item in merchantList"
              :key="item.merchantId"
              :label="item.merchantName"
              :value="item.merchantId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sassVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 认</el-button>
      </div>
    </el-dialog>
    <el-dialog width="400px" :visible.sync="updateVisible" append-to-body>
      <el-form :model="form1" ref="ruleForm" label-width="80px" class="demo-ruleForm">
        <el-form-item prop="sassId">
          <el-select v-model="form1.orderStatus" placeholder="请选择">
            <el-option value="WAIT_PAY" label="已下单待支付"></el-option>
            <el-option value="WART_SEND" label="已支付待派单"></el-option>
            <el-option value="WART_APPOINTMENT" label="已派单待预约"></el-option>
            <el-option value="WART_SITE" label="已预约待上门"></el-option>
            <el-option value="WORKING" label="已上门施工中"></el-option>
            <el-option value="WART_CHECK" label="已完工待验收"></el-option>
            <el-option value="FINISH" label="验收完成，订单完结"></el-option>
            <el-option value="REFUND_CLOSE" label="订单退款关闭"></el-option>
            <el-option value="CANCEL" label="订单取消"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateState">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { filterOrderStatus } from "@/filters/index.js";
import {
  apiOrderBList,
  apiOrderBExport,
  apiOrderBIndicator,
  apiOrderBStatusCount,
  apiOrderBUpdateStatus
} from "@/api/order.js";
import { apiMerchantPage } from "@/api/storeManager.js";
import Cards from "./components/card.vue";

export default {
  components: { Cards },
  data() {
    const _this = this;
    return {
      showSearch: false,
      sassVisible: false, //代下单选择商家弹窗
      ruleForm: {
        merchantId: ""
      },
      form1: {
        serviceOrderId: "",
        orderStatus: ""
      },
      updateVisible: false,
      rules: {
        merchantId: [
          { required: true, message: "请选择代下单的商家", trigger: "blur" }
        ]
      },
      tabs: {
        sendOrderTwo: 0,
        sendOrderTwentyFour: 0,
        appointmentOrderTwo: 0,
        appointmentOrderTwentyFour: 0,
        startOrderTwentyFour: 0,
        finishOrderTwo: 0,
        finishOrderTwentyFour: 0
      },
      statusCount: {
        waitPayCount: 0,
        waitSendCount: 0,
        waitAppointmentCount: 0,
        waitSiteCount: 0,
        workingCount: 0,
        waitCheckCount: 0
      },
      orderStatus: "",
      queryParams: { liugeFlag: true },
      pageNo: 1,
      limit: 10,
      queryPageApi: apiOrderBList,
      exportLoading: false,
      searchOption: [
        {
          type: "Input",
          field: "serviceOrderId",
          label: "订单编号",
          placeholder: "订单编号"
        },
        {
          type: "Input",
          field: "userMobile",
          label: "客户手机号",
          placeholder: "客户手机号"
        },

        {
          type: "Input",
          field: "workerMobile",
          label: "师傅手机号",
          placeholder: "师傅手机号"
        },
        {
          type: "DatePickerRange",
          field: "time",
          dateType: "daterange",
          valueFormat: "yyyy/MM/dd ",
          format: "yyyy/MM/dd",
          label: "下单时间",
          placeholder: "下单时间",
          defaultVale: []
        }
      ],
      tableOption: [
        {
          label: "订单编号",
          prop: "serviceOrderId",
          width: 80
        },
        {
          label: "服务类目",
          prop: "serviceCategoryFullName",
          width: 100
        },
        {
          label: "客户信息",
          prop: "info",
          width: 120,
          render(createElement, { row }) {
            try {
              const dom = (
                <div class="row">
                  <div>{row.userName}</div>
                  <div>{row.userMobile}</div>
                  <div>{row.address}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },
        {
          label: "师傅信息",
          prop: "worker",
          width: 120,
          render(createElement, { row }) {
            try {
              const dom = (
                <div class="row">
                  <div>{row.workerName}</div>
                  <div>{row.workerMobile}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },
        {
          label: "商家信息",
          prop: "store",
          width: 120,
          render(createElement, { row }) {
            try {
              const dom = (
                <div class="row">
                  <div>{row.merchantName}</div>
                  <div>{row.merchantContactName}</div>
                  <div>{row.merchantContactPhoneNumber}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },
        {
          label: "订单金额",
          prop: "totalPayAmount",
          width: 70,
          formatter({ orderAmount, payAmountList ,totalPayAmount}) {
            // payAmountList = payAmountList
            //   ? payAmountList.split(",").reduce((prev, cur) => {
            //       return Number(prev) + Number(cur);
            //     }, 0)
            //   : 0;
            return Number(totalPayAmount).tranFormat(2, -2, true);
          }
        },
        {
          label: "订单状态",
          prop: "orderStatus",
          width: 70,
          render(h, { row }) {
            return (
              <div>
                {filterOrderStatus(row.orderStatus)}
                <div style="color:red;">
                  {row.raiseFlag ? "有加价单待支付" : ""}
                </div>
              </div>
            );
          }
        },
        {
          label: "下单时间",
          width: 80,
          prop: "createTime",
          render(createElement, { row }) {
            try {
              const strArr = row.createTime.split(" ");
              const dom = (
                <div class="row">
                  <div>{strArr[0]}</div>
                  <div>{strArr[1]}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },

        {
          label: "操作",
          width: 80,
          prop: "",
          fixed: "right",
          render(h, { row }) {
            return h("div", [
              h("el-link", {
                domProps: {
                  innerHTML: "查看详情"
                },
                props: {
                  type: "primary"
                },
                on: {
                  click() {
                    _this.$router.push({
                      path: `/order/platformDetail?serviceOrderId=${row.serviceOrderId}&saasId=${row.saasId}`,
                      query: {}
                    });
                  }
                }
              })
              // h("el-link", {
              //   domProps: {
              //     innerHTML: "更改状态",
              //   },
              //   props: {
              //     type: "primary",
              //   },
              //   on: {
              //     click() {
              //       _this.form1.serviceOrderId = row.serviceOrderId;
              //       _this.updateVisible = true;
              //     },
              //   },
              // }),
            ]);
          }
        }
      ],
      merchantList: [],
      timer: null
    };
  },
  mounted() {
    this.getData();
  },
  destroyed() {
    clearTimeout(this.timer);
    this.timer = null;
  },
  methods: {
    onShowSearch() {
      this.showSearch = !this.showSearch;
      // 创建一个名为resizeEvent的Event对象，type属性设置为resize
      const resizeEvent = new Event("resize");

      // 使用window.dispatchEvent()方法触发事件
      window.dispatchEvent(resizeEvent);
    },
    getOrderBIndicator() {
      apiOrderBIndicator({ liugeFlag: true }).then(res => {
        if (res.code == "SUCCESS") {
          this.tabs = res.data;
          this.timer = setTimeout(() => {
            this.getOrderBIndicator();
          }, 10000);
        }
      });
    },
    getData() {
      this.getOrderBIndicator();
      apiOrderBStatusCount({ liugeFlag: true }).then(res => {
        this.statusCount = res.data;
      });
      apiMerchantPage({ pageSize: -1, pageNum: 1, merchantStatus: "YES" }).then(
        res => {
          this.merchantList = res.data;
        }
      );
    },
    onTabChange(e) {
      this.pageNo = 1;
      this.queryParams = {
        ...this.queryParams,
        payTimeStart:
          "cardSearch" in this.queryParams ? "" : this.queryParams.payTimeStart,
        payTimeEnd:
          "cardSearch" in this.queryParams ? "" : this.queryParams.payTimeEnd,
        orderStatus: this.orderStatus
      };
      if ("cardSearch" in this.queryParams) {
        delete this.queryParams.cardSearch;
      }
    },
    handleCreateOrder(mode) {
      //运营平台代下单
      if (mode == "liuGe") {
        this.sassVisible = true;
        this.ruleForm.merchantId = "";
      } else {
        this.$router.push({
          path: "/order/platformCreate",
          query: {}
        });
      }
    },
    // 确认代下单的商家
    handleConfirm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$router.push({
            path: "/order/platformCreate",
            query: {
              mode: "liuGe",
              merchantId: this.ruleForm.merchantId,
              merchantName: this.merchantList.find(
                item => item.merchantId == this.ruleForm.merchantId
              ).merchantName
            }
          });
        }
      });
    },
    onView(row) {},
    // 导出
    async handleExport() {
      this.exportLoading = true;
      const res = await apiOrderBExport({
        ...this.queryParams
      });
      if (res.code === "SUCCESS") {
        let header = [
          {
            title: "订单编号",
            prop: "serviceOrderId",
            valueType: "s"
          },
          {
            title: "服务类目",
            prop: "serviceCategoryFullName",
            valueType: "s"
          },
          {
            title: "客户信息",
            prop: "",
            valueType: "s",
            children: [
              {
                title: "客户姓名",
                prop: "userName",
                valueType: "s"
              },
              {
                title: "客户手机号",
                prop: "userMobile",
                valueType: "s"
              },
              {
                title: "地址",
                prop: "address",
                valueType: "s"
              }
            ]
          },
          {
            title: "师傅信息",
            prop: "",
            valueType: "s",
            children: [
              {
                title: "师傅姓名",
                prop: "workerName",
                valueType: "s"
              },
              {
                title: "师傅手机号",
                prop: "workerMobile",
                valueType: "s"
              }
            ]
          },
          {
            title: "商家信息",
            prop: "",
            valueType: "s",
            children: [
              {
                title: "商家名称",
                prop: "merchantName",
                valueType: "s"
              },
              {
                title: "联系人",
                prop: "merchantContactName",
                valueType: "s"
              },
              {
                title: "联系人手机号",
                prop: "merchantContactPhoneNumber",
                valueType: "s"
              }
            ]
          },
          {
            title: "订单金额",
            prop: "orderAmount",
            valueType: "n",
            numFmt: $numFmt.money
          },
          {
            title: "订单状态",
            prop: "orderStatus", //debtorTime  repaymentTime
            valueType: "s"
          },
          {
            title: "下单时间",
            prop: "createTime"
          }
        ];

        let dataSource = res.data.map(item => {
          const payAmountList = item.payAmountList
            ? item.payAmountList.split(",").reduce((prev, cur) => {
                return Number(prev) + Number(cur);
              }, 0)
            : 0;
          return {
            ...item,
            orderAmount: (item.orderAmount + payAmountList) / 100,
            orderStatus: filterOrderStatus(item.orderStatus)
          };
        });
        const option = {
          dataSource: dataSource,
          header: header,
          fileName: "六鸽订单"
        };
        window.$Json2Excel(option);
        this.exportLoading = false;
      } else {
        this.$message({
          message: "导出操作失败,请重试",
          type: "warring"
        });
        this.exportLoading = false;
      }
    },
    getStatusTxt() {
      if (this.activeStatus === "all") {
        return "";
      } else if (this.activeStatus === "wait") {
        return "待审核";
      } else if (this.activeStatus === "pass") {
        return "审核通过";
      } else if (this.activeStatus === "refuse") {
        return "审核拒绝";
      }
    },
    onCardSearch(params) {
      const { status, endTime, startTime } = params;
      this.orderStatus = status;
      this.queryParams = {
        ...this.queryParams,
        payTimeStart: startTime,
        payTimeEnd: endTime,
        cardSearch: true
      };
      // this.$refs.queryFormRefs.setFormValue({
      //   time: [startTime, endTime],
      // });
    },
    onSubmit({ values }) {
      console.log(values);
      if (values.hasOwnProperty("time")) {
        values = {
          ...values,
          payTimeStart: values.time ? values.time[0] + "00:00:00" : "",
          payTimeEnd: values.time ? values.time[1] + "23:59:59" : ""
        };
        delete values.time;
      }
      this.queryParams = { ...this.queryParams, ...values };
    },
    onClear() {
      this.queryParams = {
        orderStatus: "",
        liugeFlag: true
      };
    },
    updateState() {
      apiOrderBUpdateStatus(this.form1).then(res => {
        this.$refs.tableRefs.refresh();
      });
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-link {
  margin: 0 5px;
}
::v-deep .badge {
  position: absolute;
  right: -0px;
  top: -10px;
  transform: scale(0.9);
}
.showSearch {
  height: 0;
  overflow: hidden;
}
</style>
